package com.lance.answer.gui.answer.gk.answer.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.AnswerDTO;
import com.lance.answer.gui.answer.gk.answer.AnswerRequestDTO;
import com.lance.answer.util.HttpClientUtil;
import com.lance.answer.util.MD5Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DoAnswerTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<AnswerDTO> answerDTOS;

    public DoAnswerTask(String driverPath, LinkedBlockingDeque<AnswerDTO> answerDTOS) {
        this.driverPath = driverPath;
        this.answerDTOS = answerDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (answerDTOS.size() > 0) {
            AnswerDTO answerDTO = answerDTOS.take();
            String userName = answerDTO.getUsername();
            String password = answerDTO.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{} 课程：{}",
                    Thread.currentThread().getName(), answerDTOS.size(), userName, password,answerDTO.getSubjectName());
            run(driverPath, answerDTO);
            //todo
        }

        if (answerDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 管理学基础 2065001457555 19940419
    public static void run(String driverPath, AnswerDTO answerDTO) throws Exception {

//        Map<String, Double> urlMap = Maps.newLinkedHashMap();
//        for (AnswerRequestDTO requestDTO : answerDTO.getAnswerUrl()) {
//            urlMap.put(requestDTO.getUrl(), requestDTO.getScore());
//        }
        List<String> urlTasks = Lists.newArrayList();
        urlTasks.addAll(answerDTO.getAnswerUrl());
        Map<String, AnswerObject> answers = answerDTO.getAnswers();
        Map<String, AnswerObject> originAnswers = answerDTO.getOriginAnswers();
        String subjectName = answerDTO.getSubjectName();
        String userName = answerDTO.getUsername();
        String teacherName = answerDTO.getTeacher();
        String password = answerDTO.getPwd();
        boolean commit = answerDTO.isCommit();
        boolean push = answerDTO.isPush();


        //  String filePath = "E:\\answerInfo\\" + subjectName;
        String filePath = "libs//answerInfo//" +teacherName+"//"+ subjectName;
      //  String filePath = "D:\\project\\answer-tool\\libs\\answerInfo\\" + subjectName;

        if (!new File(filePath).exists()) {
            new File(filePath).mkdirs();
        }

        filePath = filePath + "//" + userName + ".txt";

        File completeInfoFile = new File(filePath);
        if (!completeInfoFile.exists()) {
            completeInfoFile.createNewFile();
        }
        InputStream inputStream = new FileInputStream(completeInfoFile);
        String completeInfoStr = IOUtils.toString(inputStream, "UTF-8");
        List<CompleteInfo> completeInfoList;
        try{
            completeInfoList=  JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
            if (null == completeInfoList) {
                completeInfoList = Lists.newArrayList();
            }
        }catch (Exception e){
            completeInfoList = Lists.newArrayList();
        }
        Set<String> haveCompleteHomeWorkUrlSet = Sets.newHashSet();
        for (CompleteInfo info : completeInfoList) {
            if (info.isComplete()) {
                haveCompleteHomeWorkUrlSet.add(info.getHomeworkUrl());
            }
        }

        // 定义是否开启浏览器没有这门课程
        boolean isStartChrome = false;

        for (String urlTask : urlTasks) {
            if (!haveCompleteHomeWorkUrlSet.contains(urlTask)) {
                isStartChrome = true;
                break;
            }
        }
        // FIXME TODO 2022-01-17 注释了这段代码
//        for (CompleteInfo info : completeInfoList) {
//            if ("没有这门课程！".equals(info.getSummary())) {
//                isStartChrome = false;
//                break;
//            }
//        }
        // FIXME TODO 2022-01-17 注释了这段代码

        if (!isStartChrome) {
            return;
        }

        try {
            // 随机休眠，防止浏览器同时加载，CPU受不了。
            Thread.sleep(new Random().nextInt(5)*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        WebDriver driver = Util.getDriver(driverPath);
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);

        // 判断是否找到课程
        boolean isFindSubject = false;

        //chromeDriver.navigate().refresh();
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if(subjectName.contains("经济数学基础12")){

            }

            if (!mediaTitle.equals(subjectName)) {
            //if (!mediaTitle.contains(subjectName)) {
         //   if (!mediaTitle.contains("机械CAD")) {
                continue;
            }

            isFindSubject = true;
            try {
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                //Util.switchToLast(driver);
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                try {
                    driver.close();
                    driver.quit();
                } catch (Exception e2) {

                }
            }
        }
        if (!isFindSubject) {
            try {
                CompleteInfo info = new CompleteInfo();
                info.setSummary("没有这门课程！");
                completeInfoList.add(info);
                FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
                driver.close();
                driver.quit();
                return;
            } catch (Exception e) {

            }
        }

        Util.switchToLast(driver);
        String viewUrl = driver.getCurrentUrl();
        System.err.println("viewUrl:"+viewUrl);

       try {
           if("http://xinjiang.ouchn.cn/course/view.php?id=3571".equals(viewUrl)|| // 毛泽东思想和中国特色社会主义理论体系概论 -2
                   "http://xinjiang.ouchn.cn/course/view.php?id=3570".equals(viewUrl)|| // 思想道德修养与法律基础 -2
                   "http://xinjiang.ouchn.cn/course/view.php?id=1653".equals(viewUrl)|| // 病理学与病理生理学 -2
                   "http://xinjiang.ouchn.cn/course/view.php?id=2986".equals(viewUrl)|| // 机电控制工程基础- -2
                   "http://xinjiang.ouchn.cn/course/view.php?id=3639".equals(viewUrl)){ // 机电控制与可编程序控制器技术 -2
               urlTasks.clear();
               InputStream quizInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-quiz2.section");
               List<String> list1 = IOUtils.readLines(quizInputStream,"UTF-8");
               for (String str : list1) {
                   urlTasks.add(str.split(",")[0]);
               }
           }
           if("http://xinjiang.ouchn.cn/course/view.php?id=3567".equals(viewUrl)|| // 毛泽东思想和中国特色社会主义理论体系概论 -1
                   "http://xinjiang.ouchn.cn/course/view.php?id=1961".equals(viewUrl) ||
                   "http://xinjiang.ouchn.cn/course/view.php?id=3128".equals(viewUrl) || // 病理学与病理生理学 -1
                   "http://xinjiang.ouchn.cn/course/view.php?id=3619".equals(viewUrl)|| // 机电控制工程基础- -1
                   "http://xinjiang.ouchn.cn/course/view.php?id=2984".equals(viewUrl) // 机电控制与可编程序控制器技术 -1
           ){
               urlTasks.clear();
               InputStream quizInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-quiz.section");
               List<String> list1 = IOUtils.readLines(quizInputStream,"UTF-8");
               for (String str : list1) {
                   urlTasks.add(str.split(",")[0]);
               }
           }
       }catch (Exception e){
           e.printStackTrace();
       }
//        for (String urlTask : urlTasks) {
//            System.err.println("urlTask:"+urlTask);
//        }
//        if(1>0){
//            return;
//        }

        for (String urlTask : urlTasks) {
            if (haveCompleteHomeWorkUrlSet.contains(urlTask)) {
                continue;
            }
            // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
            driver.get(urlTask);
            // FIXME 延长了
            Thread.sleep(3 * 1000);
            // 点击继续作业

            boolean isGoOn = true;

            // cell c2
            CompleteInfo completeInfo = new CompleteInfo();
            try {
                List<WebElement> tdList = driver.findElements(By.cssSelector("td[class='cell c2']"));

                for (WebElement td : tdList) {
                    String score = td.getText();
                    //     System.err.println(score);
                    if ("还未评分".equals(score)) {
                        System.err.println("还未评分");
                        isGoOn = false;
                        break;
                    }
                }
                // feedback

                String scoreString = driver.findElement(By.id("feedback")).getText();
                String[] strs = scoreString.split("/");
                String s1 =strs[0].trim() ;
                s1 =s1.replaceAll("[^.^0-9]", "");
                String s2 = strs[1].trim();
                s2 =s2.replaceAll("[^.^0-9]", "");

                float s = 0.0F;
                try {
                    s = Float.parseFloat(s1) / Float.parseFloat(s2);
                    if(Float.parseFloat(s2)<=0.0F){
                        s=100f;
                    }
                }catch (Exception e){

                }
              //  if (s > 0.80) {
          //      if (s > 0.70) {
             //   if (s > 0.70) {
                if (s > 0.70) {
          //      if (s > 0.59) {
                    completeInfo.setScore(s1);
                    System.err.println("成绩已达到，跳过");
                    isGoOn = false;
                }

            } catch (Exception e) {
            //    e.printStackTrace();
        //        Thread.sleep(2000);
            }

            if (!isGoOn) {
                boolean hasGoOn = false;
                for (WebElement we : driver.findElements(By.cssSelector("button[class='btn btn-secondary']"))) {
                    if (!Strings.isNullOrEmpty(we.getText()) && "继续上次试答".equals(we.getText().trim())) {
                        hasGoOn = true;
                    }
                }
                if (!hasGoOn) {
                    completeInfo.setComplete(true);
                    completeInfo.setHomeworkUrl(urlTask);
                    completeInfoList.add(completeInfo);
                    continue;
                }
            }

            try {
                Thread.sleep(5000);
                WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
                Thread.sleep(2 * 1000);

                try {
                    //回到试题首页
                    WebElement element = driver.findElement(By.id("quiznavbutton1"));
                    element.click();
                    Thread.sleep(2 * 1000);
                } catch (Exception e) {

                }
                try {
                    // 限制时间的答题
                    driver.findElement(By.id("id_submitbutton")).click();
                    Thread.sleep(2 * 1000);
                } catch (Exception e) {

                }
            } catch (Exception e) {
//                System.err.println("taskUrl:" + urlTask + "  occur error");
//                e.printStackTrace();
//                closeDriver(driver);
//                return;
                e.printStackTrace();
                continue;
            }
            

            // 回到首页
            //Util.goHomePageIndex(driver);
            boolean hashNextPage = true;
            while (hashNextPage) {
                try {
                    Thread.sleep(4000);
                    // 单个页面的所有题目的集合
                    List<WebElement> singlePageQuestion = Util.getSinglePageQuestionList(driver);
                    // 遍历每个问题|题目


                    for (WebElement singleSubject : singlePageQuestion) {

                        WebElement contentElement = singleSubject.findElement(By.className("content"));

                        String title;
                        title = Util.getTitle(contentElement);
                        //兼容特殊字符
                        title = Util.dealContent(title);

                        String questionCode = MD5Utils.encode(subjectName + title);

                       // System.err.println("title:"+title);
                        AnswerObject answerObject ;
                        if(answers.containsKey(questionCode)){
                            answerObject=  answers.get(questionCode);
                        }else if(originAnswers.containsKey(DealJsonString.saveZhWord(title))){
                            answerObject=  originAnswers.get(DealJsonString.saveZhWord(title));
                        }else {
                            System.out.println("答案不存在");
                            System.out.println(title);
                            Map<String, String> map = new HashMap<>();
                            map.put("答案不存在", "未能从题库中匹配到");
                            map.put("答案标题", title);
                            map.put("课程名", subjectName);
                            //  Thread.sleep(5000000);
                            continue;
                        }

                        WebElement answerElement = Util.findByClassName(contentElement, "answer");

                        if (null != answerElement) {
                            // 开始答题
                        //    Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject.getAnswers());
                            Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject);
                        } else {
                            // 如果为空就是填空题 是没有答案对比的
                            // 10-23 加了一个文件上传
                            Util.doExercise(driver, singleSubject, answerObject.getQuestionType(), answerObject.getAnswers());
                        }
                        //休眠一秒
                        TimeUnit.SECONDS.sleep(1);
                        //  FIXME 此时答案是没有保存的，要点击结束试答题
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Thread.sleep(2000);
                    // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                    WebElement nextPage = Util.findNextPage(driver);
                    if (nextPage != null) {
                        nextPage.click();
                    } else {
                        hashNextPage = false;
                        // FIXME  此时答案是没有保存的，要点击结束试答题 当没有下一页的时候，可以选择提交
                    }
                }
            }


            Thread.sleep(2000);


            WebElement submitbtns = driver.findElement(By.className("submitbtns"));
            WebElement next = submitbtns.findElement(By.cssSelector("input[name='next']"));
            next.click();
            Thread.sleep(2000);



            try{
                int sum = 0;
                int done = 0;
                for(WebElement tdWe:driver.findElements(By.cssSelector("td[class='cell c1 lastcol']"))){
                    sum++;
                    if("答案已保存".equals(tdWe.getText())
                            ||"不完整的答案".equals(tdWe.getText())){
                        done++;
                    }
                }
                // if(done*100/sum<90){
              //  if(done*100/sum<95){
            //    if(done*100/sum<85){
                if(done*100/sum<85){
                    System.err.println("---------------------");
                    // fixme
                    Thread.sleep(20000000);
                    continue;
                }
            }catch (Exception e){

            }


            if (!commit) {
                log.info("答案不提交");
                TimeUnit.SECONDS.sleep(2);
                continue;
            }

            //提交答案
            List<WebElement> saveButtons = driver.findElements(By.cssSelector("button[type='submit']"));
            //System.out.println("提交");
            //System.out.println(saveButtons.size());
            if (!CollectionUtils.isEmpty(saveButtons)) {
                for (WebElement webElement : saveButtons) {
                    String text = webElement.getText();
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }

            TimeUnit.SECONDS.sleep(3);
            //全部提交
            //提交答案



            List<WebElement> confirmation = driver.findElements(By.className("confirmation-dialogue"));
            if (!CollectionUtils.isEmpty(confirmation)) {
                for (WebElement webElement : confirmation) {
                    List<WebElement> submitElement = webElement.findElements(By.tagName("input"));
                    if (!CollectionUtils.isEmpty(submitElement)) {
                        for (WebElement element1 : submitElement) {
                            String value = element1.getAttribute("value");
                            if (value.contains("提交")) {
                                //点击确认后页面会刷新,此时为了防止丢到元素抛异常，这里直接获取第一个，不再循环
                                element1.click();
                                break;
                            }

                        }
                    }
                }
            }


            List<WebElement> submitButtons = driver.findElements(By.tagName("input"));
            if (!CollectionUtils.isEmpty(submitButtons)) {
                for (WebElement webElement : submitButtons) {
                    String text = webElement.getText();
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }

            TimeUnit.SECONDS.sleep(2);

            try {
                //判断是否符合要求
                Map<String, String> scoreMap = new HashMap<>();
                WebElement tbody = driver.findElement(By.tagName("tbody"));
                List<WebElement> trs = tbody.findElements(By.tagName("tr"));
                for (WebElement tr : trs) {
                    //th
                    WebElement th = tr.findElement(By.tagName("th"));
                    //td
                    WebElement td = tr.findElement(By.tagName("td"));
                    scoreMap.put(th.getText().trim(), td.getText().trim());
                }
                String score = scoreMap.get("分数");
                String[] strs = score.split("/");
                float s = Float.valueOf(strs[0]) / Float.valueOf(strs[1]);
                if (s < 0.80) {
                    scoreMap.put("科目", subjectName);
                    scoreMap.put("用户名", userName);
                    scoreMap.put("密码", password);
                    scoreMap.put("形考链接", urlTask);

                    if (push) {
                        HttpClientUtil.send(scoreMap);
                    }

                    System.out.println("答题不及格");
                    System.out.println(scoreMap.toString());
                } else {
                    completeInfo.setScore(score);
                    completeInfo.setComplete(true);
                    completeInfo.setHomeworkUrl(urlTask);
                    completeInfoList.add(completeInfo);
                }
            } catch (Exception e) {

            }

        }

       try {
           // 将新的完成作业的信息更新进去
           FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");

           Thread.sleep(5000);
       }catch (Exception e){

       }finally {
           closeDriver(driver);
       }
    }

    private static void closeDriver(WebDriver driver) {
        try {
            driver.close();
            driver.quit();
        } catch (Exception e) {

        }
    }

}
